// 离线地图 Service Worker
const CACHE_NAME = 'offline-map-tiles-v1';
const TILE_CACHE = 'offline-map-tiles';

// 安装事件 - 创建缓存
self.addEventListener('install', (event) => {
  console.log('Service Worker 安装中...');
  
  // 跳过等待，立即激活
  self.skipWaiting();
});

// 激活事件 - 清理旧缓存
self.addEventListener('activate', (event) => {
  console.log('Service Worker 已激活');
  
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME && cacheName !== TILE_CACHE) {
            console.log('删除旧缓存:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
  
  // 立即接管页面
  return self.clients.claim();
});

// 拦截请求
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  
  // 检查是否是地图瓦片请求
  if (url.hostname.includes('autonavi.com') && url.pathname.includes('appmaptile')) {
    event.respondWith(handleMapTileRequest(event.request));
  }
});

// 处理地图瓦片请求
async function handleMapTileRequest(request) {
  // 首先检查缓存
  const cachedResponse = await caches.match(request);
  if (cachedResponse) {
    return cachedResponse;
  }
  
  // 如果没有缓存，尝试从网络获取
  try {
    const networkResponse = await fetch(request);
    
    // 缓存响应的副本
    if (networkResponse.ok) {
      const cache = await caches.open(TILE_CACHE);
      cache.put(request, networkResponse.clone());
    }
    
    return networkResponse;
  } catch (error) {
    console.error('获取地图瓦片失败:', error);
    
    // 如果网络请求失败且没有缓存，返回一个透明瓦片
    return new Response(null, {
      status: 404,
      statusText: '地图瓦片不可用'
    });
  }
}

// 接收消息
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'CLEAR_CACHE') {
    caches.delete(TILE_CACHE).then(() => {
      console.log('地图瓦片缓存已清除');
    });
  }
}); 